<template>
  <div :class="className" :style="{height:height,width:width}" ref="chartRef" />
</template>

<script setup>
import * as echarts from 'echarts'
import 'echarts/theme/macarons' // Echarts theme
import useResize from '@/components/Echarts/Composable/resize'

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '200px'
  },
  height: {
    type: String,
    default: '200px'
  },
  name: {
    type: String,
    default: ''
  },
  chartData: {
    type: Array,
    required: true
  },
  lineWidth: {
    type: Number,
    default: 14
  },
  offsetCenter: {
    type: Array,
    default: () => ['0%', '0%']
  },
  valueFontSize: {
    type: Number,
    default: 28
  },
  titleFontSize: {
    type: Number,
    default: 14
  }
})

const chartRef = ref(null)
const chart = shallowRef(null)

// 使用 resize 组合式函数
useResize(chart)

const initChart = () => {
  if (!chartRef.value) return
  chart.value = echarts.init(chartRef.value)
  chart.value.setOption({
    color: [
      new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        {
          offset: 0,
          color: '#4494ff'
        },
        {
          offset: 1,
          color: '#5dbaff'
        }
      ])
    ],
    series: [
      {
        type: 'gauge',
        startAngle: -140,
        endAngle: 320,
        pointer: {
          show: false
        },
        progress: {
          show: true,
          overlap: false
        },
        axisLine: {
          lineStyle: {
            width: props.lineWidth
          }
        },
        splitLine: {show: false},
        axisTick: {show: false},
        axisLabel: {show: false},
        detail: {
          fontSize: props.valueFontSize,
          color: 'auto',
          formatter: '{value}%',
          valueAnimation: true,
          offsetCenter: props.offsetCenter
        },
        title: {
          offsetCenter: [0, '-30%'],
          fontSize: props.titleFontSize
        },
        data: props.chartData
      }
    ]
  })
}

// 监听 chartData 变化
watch(() => props.chartData, () => {
  nextTick(() => {
    initChart()
  })
}, {deep: true})

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  if (!chart.value) return
  chart.value.dispose()
  chart.value = null
})
</script>
